package com.onlinevideo.servlet;

import cn.hutool.json.JSONUtil;
import com.onlinevideo.data.ResultBean;
import com.onlinevideo.entity.*;
import com.onlinevideo.service.MessageService;
import com.onlinevideo.service.impl.HistoryServiceImpl;
import com.onlinevideo.service.impl.MessageServiceImpl;
import com.onlinevideo.service.impl.VideoItemServiceImpl;
import com.onlinevideo.service.impl.VideoServiceImpl;
import org.apache.commons.fileupload.FileItem;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class VideoServlet extends BaseServlet {

    private PrintWriter writer = null;
    private HistoryServiceImpl historyService = new HistoryServiceImpl();
    private VideoServiceImpl videoService = new VideoServiceImpl();
    private VideoItemServiceImpl videoItemService = new VideoItemServiceImpl();
    private MessageService messageService = new MessageServiceImpl();

    //播放视频
    protected void play(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取用户，用于判断是否登录
        HttpSession session = req.getSession();
        User user = (User) session.getAttribute("user");

        //获取视频id，查出数据库中的视频及相关子集
        String videoIdStr = req.getParameter("videoId");
        Long videoId = Long.valueOf(videoIdStr);
        Video video = videoService.queryByIdS1(videoId);
        List<VideoItem> videoItems = videoItemService.queryByVideoId(videoId);
        req.setAttribute("video", video);
        req.setAttribute("videoItems", videoItems);
        //用户不为空 添加历史记录 添加播放量
        if (user != null) {
            Long id = user.getId();
            //根据历史记录的时间确定播放量是否+1
            List<History> histories = historyService.queryByUserAndVideo(id, videoId);
            //有历史则判断
            if (histories.size() > 0) {
                History history = histories.get(0);
                long lastPlay = Long.parseLong(history.getTime());
                //播放的间隔 大于一天播放量+1
                if (System.currentTimeMillis() - lastPlay > 1000 * 60 * 30) {
                    video.setPlayTotalCount(video.getPlayTotalCount()+1);
                    videoService.update(video);
                }
            }else {
                //无历史记录则说明第一次看，播放量+1  （用户不能删除一小时以内的历史记录）
                video.setPlayTotalCount(video.getPlayTotalCount()+1);
                videoService.update(video);
            }
            //记录历史
            historyService.addHistory(id, videoId);
        }
        req.getRequestDispatcher("/WEB-INF/view/video_play.jsp").forward(req,resp);
    }

    //视频选集方法
    protected void update(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        String idStr = req.getParameter("id");
        long id = 1L;
        if (idStr != null) {
            id = Long.parseLong(idStr);
        }
        VideoItem videoItem = videoItemService.queryById(id);
        resp.getWriter().write(videoItem.getUrl());
    }

    /***
     * 处理上传视频事件
     */
    protected void upload(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        writer = resp.getWriter();
        //获取用户信息
        HttpSession session = req.getSession();
        User user = (User) session.getAttribute("user");
        //传递数据
        Map<String, Object> videoInfo = new HashMap<>();
        String videoName = (String) req.getAttribute("videoName");
        Long categoryId = Long.valueOf((String) req.getAttribute("categoryId"));
        String videoDescription = (String) req.getAttribute("videoDescription");
        List<FileItem> fileDomain = (List<FileItem>) req.getAttribute("fileDomain");
        if (videoName == null || videoName.length() <= 0) {
            writer.write(JSONUtil.toJsonStr(ResultBean.scOperationError("视频上传失败")));
            return;
        }
        if (videoDescription == null || videoDescription.length() <= 0) {
            writer.write(JSONUtil.toJsonStr(ResultBean.scOperationError("视频上传失败")));
            return;
        }
        if (fileDomain == null || fileDomain.size() <= 0) {
            writer.write(JSONUtil.toJsonStr(ResultBean.scOperationError("视频上传失败")));
            return;
        }
        videoInfo.put("videoName", videoName);
        videoInfo.put("categoryId", categoryId);
        videoInfo.put("videoDescription", videoDescription);
        videoInfo.put("fileDomain", fileDomain);
        videoInfo.put("userId", user.getId());


        //处理用户发送过来的数据
        int upload = videoService.upload(videoInfo);

        //处理后的返回结果
        if (upload > 0) {
            writer.write(JSONUtil.toJsonStr(ResultBean.scOperationSuccess("视频上传成功,请重新刷新页面")));
            Message message = new Message(null, user.getId(), "您的视频\"" + videoName + "\"已上传，正在审核", 0, String.valueOf(System.currentTimeMillis()));
            messageService.insert(message);
        } else {
            writer.write(JSONUtil.toJsonStr(ResultBean.scOperationError("视频上传失败")));
        }

    }
    //修改视频信息
    protected void updateVideoInfo(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        User user = (User) req.getSession().getAttribute("user");
        Map<String, Object> videoInfo = new HashMap<>();
        writer = resp.getWriter();
        String videoId = (String) req.getAttribute("videoId");
        String videoDes = (String) req.getAttribute("videoDes");
        String videoName = (String) req.getAttribute("videoName");
        Long videoCategoryId = Long.valueOf((String) req.getAttribute("videoCategoryId"));
        List<FileItem> fileDomain = (List<FileItem>) req.getAttribute("fileDomain");
        if (videoName == null || videoName.length() <= 0) {
            writer.write(JSONUtil.toJsonStr(ResultBean.scOperationError("视频上传失败")));
            return;
        }
        if (videoDes == null || videoDes.length() <= 0) {
            writer.write(JSONUtil.toJsonStr(ResultBean.scOperationError("视频上传失败")));
            return;
        }
        if (fileDomain == null || fileDomain.size() <= 0) {
            writer.write(JSONUtil.toJsonStr(ResultBean.scOperationError("视频上传失败")));
            return;
        }
        videoInfo.put("videoName", videoName);
        videoInfo.put("videoId", Long.valueOf(videoId));
        videoInfo.put("videoCategoryId", videoCategoryId);
        videoInfo.put("videoDes", videoDes);
        videoInfo.put("fileDomain", fileDomain);
        videoInfo.put("userId", user.getId());

        //上面是获取数据

        //调用service
        int update = videoService.update(videoInfo);
        //下面返回结果
        if (update >= 0) {
            writer.write(JSONUtil.toJsonStr(ResultBean.scOperationSuccess("视频修改成功")));
        } else {
            writer.write(JSONUtil.toJsonStr(ResultBean.scOperationError("视频修改失败")));
        }
    }



    /***
     * 删除全部视频
     * @param req 请求参数
     * @param resp 响应参数
     */
    protected void deleteVideo(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        writer = resp.getWriter();
        Long videoId = Long.valueOf(req.getParameter("videoId"));
        int delete = videoService.delete(videoId);
        if (delete > 0) {
            writer.write(JSONUtil.toJsonStr(ResultBean.scOperationSuccess("视频删除成功")));
        } else {
            writer.write(JSONUtil.toJsonStr(ResultBean.scOperationError("视频删除视频失败，视频可能不存在或重复提交")));
        }
    }
    //删除子集
    protected void deleteVideoItem(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Long videoItemId = Long.valueOf(req.getParameter("videoItemId"));
        int delete = videoItemService.delete(videoItemId);
        if (delete > 0) {
            resp.getWriter().write("");
        } else {
            resp.getWriter().write("x");
        }
    }

    /**
     * 查询视频子集
     *
     * @param req  请求头
     * @param resp 响应头
     */
    protected void queryVideoItemByVideoId(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        writer = resp.getWriter();
        Long videoId = Long.valueOf(req.getParameter("videoId"));
        List<VideoItem> videoItems = videoItemService.queryByVideoId(videoId);
        writer.write(JSONUtil.toJsonStr(videoItems));
    }

    //
    protected void getVideoListQueryLikeByCondition(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String result = req.getParameter("result");
        String pageNoStr = req.getParameter("pageNo");
        String category = req.getParameter("category");
        String videoName = req.getParameter("videoName");
        HttpSession session = req.getSession();
        Integer pageNo = null;
        if (pageNoStr != null) {
            pageNo = Integer.valueOf(pageNoStr);
        }
        Map<String, Object> maps = new HashMap<>();
        maps.put("pageNo", pageNo);
        maps.put("category", category);
        maps.put("videoName", videoName);
        maps.put("session", session);
        videoService.page(maps);

        if ("json".equals(result)) {
            resp.getWriter().write(JSONUtil.toJsonStr(ResultBean.scOperationSuccess("请求成功")));
        } else {
            resp.sendRedirect("../gateway?action=search");
        }
    }

    //视频审核
    protected void checkVideo(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();

        writer = resp.getWriter();
        String videoIdStr = req.getParameter("videoId");
        if (videoIdStr == null) {
            return;
        }
        boolean matches = videoIdStr.matches("[0-9]+");
        if (!matches) {
            return;
        }
        Long videoId = Long.valueOf(videoIdStr);
        String pass = req.getParameter("pass");
        Video video = videoService.queryById(videoId);
        if ("pass".equals(pass)) {
            video.setVideoStatus(1);
            int update = videoService.update(video);
            writer.write(JSONUtil.toJsonStr(ResultBean.scOperationSuccess("视频已通过")));
            Message message = new Message(null, video.getUserId(), "您的视频\"" + video.getVideoName() + "\"审核已通过", 0, String.valueOf(System.currentTimeMillis()));
            messageService.insert(message);

        } else if ("delete".equals(pass)) {
            String reason = req.getParameter("reason");
            if (reason == null) {
                reason="无";
            }
            videoService.delete(videoId);
            writer.write(JSONUtil.toJsonStr(ResultBean.scOperationSuccess("视频已未通过，已经删除")));
            Message message = new Message(null, video.getUserId(), "您的视频\"" + video.getVideoName() + "\"审核未通过，请重新上传，原因："+reason, 0, String.valueOf(System.currentTimeMillis()));
            messageService.insert(message);
        }
    }
}
